<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            />
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
          >
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table
        :data="userlist"
        :border="true"
        stripe
      >
        <el-table-column
          type="index"
          label="#"
        />
        <el-table-column
          prop="username"
          label="姓名"
        />
        <el-table-column
          prop="email"
          label="邮箱"
        />
        <el-table-column
          prop="mobile"
          label="电话"
        />
        <el-table-column
          prop="role_name"
          label="角色"
        />
        <el-table-column
          prop="mg_statue"
          label="状态"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row.id)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            />
            <!-- 删除 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeUserById(scope.row.id)"
            />
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容 -->
      <span>
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="ruleFormRef"
          label-width="70px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input v-model="addForm.username" />
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
          >
            <el-input v-model="addForm.password" />
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="addForm.email" />
          </el-form-item>
          <el-form-item
            label="手机"
            prop="mobile"
          >
            <el-input v-model="addForm.mobile" />
          </el-form-item>
        </el-form></span>
      <!-- 底部区 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUser"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修i该用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogclosed"
    >
      <!-- 内容 -->
      <span>
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item
            label="用户名"
          >
            <el-input
              v-model="editForm.username"
              disabled
            />
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="editForm.email" />
          </el-form-item>
          <el-form-item
            label="电话"
            prop="mobile"
          >
            <el-input v-model="editForm.mobile" />
          </el-form-item>
        </el-form>
      </span>
      <!-- 脚部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editUserInfo"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesDialogVisible"
      width="50%"
      @close="setRoleDialogClose"
    >
      <!-- 内容区域 -->
      <span>
        <div>
          <p>当前用户:{{ userInfo.username }}</p>
          <p>当前角色:{{ userInfo.role_name }}</p>
          <p>分配新角色:
            <el-select
              v-model="selectedRoleId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in roelist"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </p>
        </div>
      </span>
      <!-- 脚部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveRoleInfo"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function () {
    // 验证邮箱
    var checkEmail = (rule, val, cb) => {
      var regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(val)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号
    var checkMobile = (rule, val, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(val)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 控制分配角色显示与隐藏
      setRolesDialogVisible: false,
      editFormRules: {
        email: [ { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' } ],
        mobile: [{ required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' } ]
      },
      // 获取用户列表对象参数
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      // 添加用户对话框显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''

      },
      // 验证规则对象
      addFormRules: {
        username: [ { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
        password: [ { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }],
        email: [ { required: true, message: '请输入邮箱', trigger: 'blur' }, { validator: checkEmail, trigger: 'blur' } ],
        mobile: [ { required: true, message: '请输入电话', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' } ]
      },
      // 修改i用户对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑用户信息对象
      editForm: {},
      // 需要被分配角色的的用户
      userInfo: {},
      // 角色列表
      roelist: [],
      // 被选上中的角色id
      selectedRoleId: ''
    }
  },
  methods: {
    // 分配角色对话框关闭
    setRoleDialogClose () {
      this.selectedRoleId = ''
      this.userInfo = {}
    },
    // 分配角色
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.info('请这角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
      this.getUserList()
      this.setRolesDialogVisible = false
    },
    // 展示分配角色对话框
    async  setRole (userInfo) {
      this.userInfo = userInfo
      // 展示对话框之前 获取所有的角色
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败哦')
      }
      this.roelist = res.data
      this.setRolesDialogVisible = true
    },
    async removeUserById (id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getUserList()
    },
    // 修改信息
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`users/` + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('更新用户信息成功')
      })
    },
    // 监听修改用户对话框使劲按
    editDialogclosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 展示修改用户对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    addUser () {
      this.$refs.ruleFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        // 发起请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        } else {
          this.$message.success('添加用户成功')
          this.addDialogVisible = false
          // 从新获取列表
          this.getUserList()
        }
      })
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed () {
      this.$refs.ruleFormRef.resetFields()
    },
    getUserList: async function () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取用户列表失败')
        return
      }
      this.userlist = res.data.users
      console.log(res.data)
      this.total = res.data.total
    },
    // 改变pagesize事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 页码改变事件处理函数
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 用户状态切换按钮事件函数
    async  userStateChanged (userinfo) {
      const { data: res } = await this.$http.put(`/users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        this.$message.error('更新用户状态失败')
        userinfo.mg_state = !userinfo.mg_state
        return
      }
      this.$message.success('更新状态成功')
    }
  },
  created () {
    this.getUserList()
  }
}
</script>

<style scoped lang="less">

</style>
